package com.exam.dao.base;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.classic.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;



public class BaseDaoImpl<T> implements IBaseDao<T> {

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {//获得超类的泛型参数的实际类型
		this.entityClass = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	
	private Class<T> entityClass;
	
	public Class<T> getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Autowired
	private HibernateTemplate hibernateTemplate;
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	public Session getSession() {
		return this.getHibernateTemplate().getSessionFactory().getCurrentSession();
	}
	
	@Override
	public Serializable save(T entity) {
		return hibernateTemplate.save(entity);
	}

	@Override
	public void update(T entity) {
		hibernateTemplate.update(entity);
	}

	@Override
	public void delete(T entity) {
		hibernateTemplate.delete(entity);
	}

	@Override
	public List<T> findAll() {
		return findByCriteria();
	}
	
	

	@SuppressWarnings("unchecked")
	public List<T> findByCriteria(Criterion... criterions) {
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(getEntityClass());
		for (Criterion criterion : criterions) {
			detachedCriteria.add(criterion);
		}
		return getHibernateTemplate().findByCriteria(detachedCriteria);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public T findByKey(Serializable id) {
		return (T) this.getSession().get(getEntityClass(), id);
	}

	@Override
	public Serializable merge(T entity) {
		return (Serializable) hibernateTemplate.merge(entity);
	}

	@Override
	public void saveOrUpdate(T entity) {
		hibernateTemplate.merge(entity);
	}


}
